<?php
    require_once ("Includes/session.php");
    require_once ("Includes/simplecms-config.php"); 
    require_once ("Includes/connectDB.php");
    require_once("conf.php");   
    include("Includes/header.php"); 
    if (!logged_on())
    {
        header ("Location: logon.php");
    }


    $val = trim($_SERVER['QUERY_STRING']);
    if(empty($val))
    {
        header ("Location: Student_ExamSelection.php");
    }
    else
    {
        if(!is_doing_exam())
        {
            $temp =explode('=', $val);
            $_SESSION['ExamID'] =  $temp[1];
        }
    }

    if(!is_doing_exam())
    {
        echo "<script type='text/javascript'>
        
        function myFunc() 
        {
            document.getElementById('rightSide').style.visibility = 'hidden';
            document.getElementById('questionBody').style.visibility = 'hidden';
            document.getElementById('startExam').style.visibility = 'visible';
        }

        </script>";
        
    }

    if(isset($_POST['Return']))
    {
        $tempUserID = $_SESSION['userid'];
        $tempUserName = $_SESSION['username'];
        $_SESSION = array();
		session_destroy();
        session_start();
        $_SESSION['userid'] = $tempUserID;
        $_SESSION['username'] = $tempUserName;
	    header ("Location: Student_ExamSelection.php");
    }

    if(isset($_POST['startExam']))
    {
        $_SESSION['Viewing'] = "0";
        $_SESSION['ExamStarted'] = 1;
        $_SESSION['CurrentQuestion'] = 1;
        for($i=1; $i<=30; $i++)
        {
            $_SESSION['q_'.$i] = 0;
        }
        echo "<script type='text/javascript'>
        

        function myFunc() 
        {
            document.getElementById('rightSide').style.visibility = 'visible';
            document.getElementById('questionBody').style.visibility = 'visible';
            document.getElementById('startExam').style.visibility = 'hidden';
        }

        </script>";
    }

    if(isset($_POST['FinishExam']) && $_SESSION['Viewing'] != 1)
    {
        
        for($cnt = 1; $cnt<=30;$cnt++)
        {
            if(!isset($_SESSION['q_'.$cnt]) || $_SESSION['q_'.$cnt]=='0')
            {
                echo "<script type='text/javascript'>alert('You have to answer all questions before submitting !')</script>";
                $end = true;
                break;
            }
           
        }

        
        if(!isset($end))
        {
            $getanswers = "SELECT id,AIndex FROM questions WHERE exam_id = ?";

            $fexam = $databaseConnection->prepare($getanswers);
            $fexam->bind_param('s',$_SESSION['ExamID']);
            $fexam->execute();
            $fexam->store_result();
            if($fexam->error)
            {
                echo "<script type='text/javascript'>alert('Database query failed!')</script>";
            }
            elseif($fexam->num_rows != 30)
            {
                echo "<script type='text/javascript'>alert('An error occured !')</script>";
            }
            else
            {
                $fexam->bind_result($id,$ans);
                $index = 1;
                while($fexam->fetch())
                {
                    $_SESSION['a_'.$index] = $ans;
                    $_SESSION['id_'.$index] = $id;
                    $index = $index + 1;
                    
                
                }
  
            }

            $EID = $_SESSION['ExamID'];
            $user_id = $_SESSION['userid'];
            
            $mark = 0;
            for($i = 1; $i<=30;$i++)
            {
                if($_SESSION['q_'.$i] == $_SESSION['a_'.$i])
                {
                    $mark++;
                }
                
            }
            $query1 = "INSERT INTO exam_attempts (exam_id, user_id , anstime, mark) VALUES (? , ? , NOW(), ?)";

            $statement = $databaseConnection->prepare($query1);
            $statement->bind_param('ddd', $EID , $user_id, $mark);
            $statement->execute();
            $statement->store_result();
            $atmptid = $statement->insert_id;

            $creationWasSuccessful = $statement->affected_rows == 1 ? true : false;
            if ($creationWasSuccessful)
            {
                $insert = "INSERT INTO answers (answer , exam_attempt_id , question_id) VALUES ( ? , $atmptid , ?)";
                $statement = $databaseConnection->prepare($insert);
                


                for($cnt = 1; $cnt<=30;$cnt++)
                {
                    $statement->bind_param('ss', $_SESSION['q_'.$cnt] , $_SESSION['id_'.$cnt]);
                    $statement->execute();
                    $statement->store_result();
                    
                    $creationWasSuccessful = $statement->affected_rows == 1 ? true : false;
                    if($creationWasSuccessful)
                    {
                        
                    }
                    else
                    {
                        echo "<script type='text/javascript'>alert('An error occured at question $cnt !')</script>";
                        $error = 1;
                    }
                }

                if(!isset($error))
                {
                    echo "<script type='text/javascript'>alert('Answer committed successfully! \\n You Scored $mark / 30 ')</script>";
                    $_SESSION['Viewing'] = 1;
                }
                else
                {
                    echo "<script type='text/javascript'>alert('An error occured while committing your answer!')</script>";
                }
                
            }
            else
            {
                echo "<script type='text/javascript'>alert('An error occured !')</script>";
            }

            $statement->close();


        }


    }
    $prevQ = 0;
    if(is_doing_exam())
    {
        if(isset($_POST['Previous']))
        {
            if($_SESSION['CurrentQuestion'] != 1)
            {
                $prevQ = $_SESSION['CurrentQuestion'];
                $_SESSION['CurrentQuestion'] = $_SESSION['CurrentQuestion']- 1;
            }
            else
            {
                echo "<script type='text/javascript'>alert('First Question')</script>";
            }
        }
        if(isset($_POST['Next']))
        {
            if($_SESSION['CurrentQuestion'] != 30)
            {
                $prevQ = $_SESSION['CurrentQuestion'];
                $_SESSION['CurrentQuestion'] = $_SESSION['CurrentQuestion'] + 1;
                
            }
            else
            {
                $_SESSION['q_30'] = $_POST['choice'];
                echo "<script type='text/javascript'>alert('Last Question')</script>";
                $_SESSION['q_30'] = $_POST['choice'];
            }
        }
        for($i2=1;$i2<=30;$i2++)
        {
            $checker = 'GoTo'.$i2;
            if(isset($_POST[$checker]))
            {
                $prevQ = $_SESSION['CurrentQuestion'];
                $_SESSION['CurrentQuestion'] = $i2;
                break;
            }
        }
        
        $indexToSave = "q_$prevQ";
        //echo $indexToSave;
        if(isset($_POST['choice']))
            $_SESSION[$indexToSave] = $_POST['choice'];
        $getQuestion = "SELECT question, c1, c2, c3, c4 FROM Questions where exam_id=? order by id LIMIT ?,1";
        $statement = $databaseConnection->prepare($getQuestion);
        $getID = $_SESSION['CurrentQuestion']- 1;
        $statement->bind_param('dd',$_SESSION['ExamID'], $getID);
        $statement->execute();
        $statement->store_result();

        if ($statement->num_rows == 1 )
        {
            $Qtext = NULL;
            $c1 = NULL;
            $c2 = NULL;
            $c3 = NULL;
            $c4 = NULL;
            $statement->bind_result($Qtext, $c1, $c2, $c3, $c4);
            $statement->fetch();



            //echo $prevQ;
            //echo $Qtext;
            //$result = $statement->get_result();
            //$row = $result->fetch_array();
            //echo $row;
        }
        else
        {
            echo 'Error'. $statement->num_rows;
        }
    }
    
?>
<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", myFunc, false);
</script>
<div id="add" style="height: 450px; width: 40%">
    <form method="post">
        <fieldset>
            <div id="questionBody">
                <div id="Question">
                    <?php echo $Qtext;?>
                </div>
                <br />
                <div id="choices" style="padding-left: 5%;">
                    Please select one answer:
                    <br/>
                    <br/>
                    1- <input type="radio" name="choice" value="1" <?php if($_SESSION['q_'.$_SESSION['CurrentQuestion']] == '1') echo "Checked='true'"; if($_SESSION['Viewing'] == '1') echo "disabled='true'"; ?> ><?php echo $c1;?>  </input>
                    <br/>
                    <br/>
                    2- <input type="radio" name="choice" value="2" <?php if($_SESSION['q_'.$_SESSION['CurrentQuestion']] == '2') echo "Checked='true'"; if($_SESSION['Viewing'] == '1') echo "disabled='true'";?> ><?php echo $c2;?>  </input>
                    <br/>
                    <br/>
                    3- <input type="radio" name="choice" value="3" <?php if($_SESSION['q_'.$_SESSION['CurrentQuestion']] == '3') echo "Checked='true'"; if($_SESSION['Viewing'] == '1') echo "disabled='true'";?> ><?php echo $c3;?>  </input>
                    <br/>
                    <br/>
                    4- <input type="radio" name="choice" value="4" <?php if($_SESSION['q_'.$_SESSION['CurrentQuestion']] == '4') echo "Checked='true'"; if($_SESSION['Viewing'] == '1') echo "disabled='true'";?> ><?php echo $c4;?>  </input>
                    <br/>
                    <br/>
                </div>    
                <input type="submit" id="Previous" name="Previous" value="Previous"/>
                <input type="submit" id="Next" name="Next" value="Next"/>
            </div>            
            <div id="startExam" class="MainContent" style="visibility: hidden; z-index: 5; position: absolute; top: 22%; left: 5%;">
                <input type="submit" value="Start Exam" name="startExam" id="startExam" />
            </div>
        </fieldset>
    </form>
</div>
    <div id="rightSide">
     <div id="edit" style="height: 400px; width: 25%">
            <h2>Navigator</h2>
            <form method="post">
                <table style="width: 83%" border="1">
                <?php
                    for($i=1; $i<=30;$i++)
                    {
                        echo '<tr>';

                    
                        echo '<td>';
                        echo $i;
                        echo '</td>';

                        if($_SESSION['Viewing'] != "1")
                        {
                            if(!isset($_SESSION['q_'.$i]) || $_SESSION['q_'.$i] == 0)
                            {
                                echo '<td bgcolor="#FF2F2F">';
                                echo 'Unanswered';
                            }
                            else
                            {
                                echo '<td bgcolor="#00FF00">';
                                echo 'Answer:'.$_SESSION['q_'.$i];
                            }
                            echo '</td>';
                        }
                        else
                        {
                            if($_SESSION['q_'.$i] == $_SESSION['a_'.$i])
                            {
                                echo '<td bgcolor="#00FF00">';
                                echo 'Correct Answer';
                            }
                            else
                            {
                                echo '<td bgcolor="#FF2F2F">';
                                echo 'Wrong Answer, Correct is: '.$_SESSION['a_'.$i];
                            }
                            echo '</td>';
                        }

                        echo '<td>';
                        echo '<input type="submit" name="GoTo'.$i.'" value="Go" style="width: 100%"/>';
                        echo '</td>';

                        echo '</tr>';
                    }
                    
                ?>
            
                </table>
            </form>
            
        </div>
        
        <form method="post" class="MainContent" style="float: right; width: 25%; padding-right: 19%; padding-top: 0; ">
            <?php
                if($_SESSION['Viewing'] != "1")
                {
                    echo '<input type="submit" style="width: 100%; height: 50px;" name="FinishExam" value="Finish Exam" />';
                }
                else
                {
                    echo '<input type="submit" style="width: 100%; height: 50px;" name="Return" value="Return" />';
                }
                
            ?>
            
        </form>
    </div>
</div>

<?php include ("Includes/footer.php"); ?>